<?php
/* $Id$ */
/*
	traffic_limit_edit.php
	part of stairway

	Copyright (C) 2009 Wang Zhongliang (wzlsh629@163.com)
	All rights reserved.

	Redistribution and use in source and binary forms, with or without
	modification, are permitted provided that the following conditions are met:

	1. Redistributions of source code must retain the above copyright notice,
	   this list of conditions and the following disclaimer.

	2. Redistributions in binary form must reproduce the above copyright
	   notice, this list of conditions and the following disclaimer in the
	   documentation and/or other materials provided with the distribution.

	THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
	INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
	AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
	AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
	OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
	SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
	INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
	CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
	POSSIBILITY OF SUCH DAMAGE.
*/

##|+PRIV
##|*IDENT=page-traffic_limit_edit
##|*NAME=traffic_limit_edit page
##|*DESCR=Allow access to the 'Traffic Limit Edit' page.
##|*MATCH=traffic_limit_edit.php*
##|-PRIV
require_once('guiconfig.inc');

$specialsrcdst = explode(" ", "any");

if (!is_array($config['dummynet']['pipe'])) {
    $config['dummynet']['pipe'] = array();
}

$a_pipe = &$config['dummynet']['pipe'];

$id = $_GET['id'];
if (is_numeric($_POST['id']))
    $id = $_POST['id'];

if (isset($id) && $a_pipe[$id]) {

    if (!isset($a_pipe[$id]['method']))
        $pconfig['method'] = 'limit';
    else
        $pconfig['method'] = $a_pipe[$id]['method'];

    $pconfig['up'] = $a_pipe[$id]['up'];
    $pconfig['up_unit'] = $a_pipe[$id]['up_unit'];
    $pconfig['down'] = $a_pipe[$id]['down'];
    $pconfig['down_unit'] = $a_pipe[$id]['down_unit'];
    $pconfig['descr'] = $a_pipe[$id]['descr'];
    
    address_to_pconfig($a_pipe[$id]['ip'], $pconfig['ip'],
        $pconfig['mask'], $pconfig['not'],
        $pconfig['beginport'], $pconfig['endport']);

    foreach($a_pipe[$id]['queue'] as $q)
    {
        $tmp = array();
        $tmp[] = $q['ip']['any'] ? 'any' : $q['ip']['address'];

        $tmp[] = $q['weight'];
        $pconfig['adv_txt'] .= implode(',', $tmp) . "\n";
    }

} else {

    $pconfig['method'] = 'limit';
    $pconfig['up_unit'] = "Kb";
    $pconfig['down_unit'] = "Kb";
    address_to_pconfig(array('any'), $pconfig['ip'],
        $pconfig['mask'], $pconfig['not'],
        $pconfig['beginport'], $pconfig['endport']);    
}

if ($_POST) {

    if($_POST['method'] == 'share')
    {
        $_POST['method'] = $_POST['sharetype'];
    }

    $pconfig = $_POST;    
    
    if (is_specialnet($_POST['type'])) {
        $_POST['ip'] = $_POST['type'];
        $_POST['mask'] = 0;
    } else if ($_POST['type'] == "single") {
        $_POST['mask'] = 32;
    }
    
    if ($_POST['beginport_cust'] && !$_POST['beginport'])
        $_POST['beginport'] = $_POST['beginport_cust'];
    if ($_POST['endport_cust'] && !$_POST['endport'])
        $_POST['endport'] = $_POST['endport_cust'];

    if ($_POST['beginport'] == "any") {
        $_POST['beginport'] = 0;
        $_POST['endport'] = 0;
    } else {
        if (!$_POST['endport'])
            $_POST['endport'] = $_POST['beginport'];
    }
    if ($_POST['endport'] == "any")
        $_POST['endport'] = $_POST['beginport'];

            
    /*  run through $_POST items encoding HTML entties so that the user
     *  cannot think he is slick and perform a XSS attack on the unwilling 
     */
//    foreach ($_POST as $key => $value) {
//        $temp = $value;
//        $newpost = htmlentities($temp);
//        if($newpost <> $temp)        
//            $input_errors[] = "检测到无效字符($temp)请移除无效字符并保存。";     
//    }

    /* input validation */
    if(empty($_POST['up']) && empty($_POST['down']))
    {
        $input_errors[] = "请指定上传或下载带宽大小";
    }

    if (!(is_specialnet($_POST['ip']) || ($_POST['type'] == "single"))) {
        $reqdfields[] = "mask";
        $reqdfieldsn[] = "掩码";
    }    

    if($_POST['type'] == "network") {
        if(is_alias($_POST['item']))
            $input_errors[] = "你输入有效的网段。";
    }

    if (!is_specialnet($_POST['type'])) {
        if (($_POST['item'] && !is_ipaddroranyalias($_POST['item']))) {
            $input_errors[] = "请输入有效的IP地址或别名。";
        }
        if (($_POST['mask'] && !is_numericint($_POST['mask']))) {
            $input_errors[] = "请输入有效的子网掩码。";
        }
    }      
    
    if($_POST['method'] == 'weight')
    {
        if (($_POST['beginport'] != 0) && ($_POST['beginport'] != "any")) {
            if ($_POST['beginport'] != $_POST['endport'])
                    $port = $_POST['beginport'] . "-" . $_POST['endport'];
            else
                    $port = $_POST['beginport'];
        }

        if(alias_expand($_POST['beginport'])) {
                $port = $_POST['beginport'];
        }
                
        $data = $_POST['adv_txt'];
        $lines = explode("\n", $data);
        $queue = array();
        foreach($lines as $line)
        {
            $queueent = NULL;
            $line = trim($line);
            if(!$line)
            {
                continue;
            }
            $fields = explode(',', $line);
            $count = count($fields);
            if($count != 2)
            {
                $input_errors[] = "高级编辑输入格式有误。";
                break;
            }
            if(is_subnet($fields[0]) || is_ipaddroralias($fields[0]) || is_specialnet($fields[0]))
            {
                $queueent['ip']['address'] = $fields[0];
            }
            else if($fields[0] == 'any')
            {
                $queueent['ip']['any'] = true;
            }
            else
            {
                $input_errors[] = "{$fields[0]}不是有效的网段或IP或别名。";
                break;
            }
            
            if($port)
            {
                $queueent['ip']['port'] = $port;
            }

            if($fields[$count - 1] < 1 || $fields[$count - 1] > 100)
            {
                $input_errors[] = "权重必须在1-100之间。";
                break;                
            }
            $queueent['weight'] = $fields[$count - 1];
            
            $queue[] = $queueent;
        }
    }    
    
    do_input_validation($_POST, $reqdfields, $reqdfieldsn, &$input_errors);

    if (!$input_errors) {
        $pipeent = array();
        $pipeent['method'] = $_POST['method'];
        $pipeent['up'] = $_POST['up'];
        $pipeent['up_unit'] = $_POST['up_unit'];
        $pipeent['down'] = $_POST['down'];
        $pipeent['down_unit'] = $_POST['down_unit'];
        
        if($pipeent['method'] != 'weight')
        {
            pconfig_to_address($pipeent['ip'], $_POST['ip'],
                $_POST['mask'], $_POST['not'],
                $_POST['beginport'], $_POST['endport']);
        }
        else
        {
            $pipeent['queue'] = $queue;
        }
        $pipeent['descr'] = $_POST['descr'];
        
        if (isset($id) && $a_pipe[$id]){
            $a_pipe[$id] = $pipeent;
        } else {
            $a_pipe[] = $pipeent;
        }
        write_config();
        touch($d_dummynetconfdirty_path);

        header("Location: traffic_limit.php");

    }
}

$pgtitle = array("流量管理", "流量限制", "规则", "编辑");
$pgmenu = array('traffic', '/traffic_limit.php');
$closehead = false;

include("head.inc");

?>

</head>

<body link="#0000CC" vlink="#0000CC" alink="#0000CC">
<?php include("fbegin.inc"); ?>
<?php if ($input_errors) print_input_errors($input_errors); ?>

<form action="traffic_limit_edit.php" method="post" name="iform" id="iform">
    <table width="100%" border="0" cellpadding="6" cellspacing="0">
        <tr>
            <td colspan="2" valign="top" class="listtopic">流量限制规则编辑</td>
        </tr>   
        <tr>
            <td width="22%" valign="top" class="vncellreq">上行带宽</td>
            <td width="78%" class="vtable">
	            <input autocomplete='off' name="up" type="text" class="formfldalias" id="address" size="30" value="<?=htmlspecialchars($pconfig['up']); ?>">
	            <select name="up_unit" class="formselect">
                   <option value="Kb" <?php if($pconfig['up_unit'] == 'Kb') echo 'selected'; ?>>Kbit/s</option>
                   <option value="Mb" <?php if($pconfig['up_unit'] == 'Mb') echo 'selected'; ?>>Mbit/s</option>
                   <option value="KB" <?php if($pconfig['up_unit'] == 'KB') echo 'selected'; ?>>KByte/s</option>
                   <option value="MB" <?php if($pconfig['up_unit'] == 'MB') echo 'selected'; ?>>MByte/s</option>
	            </select>
            </td>
        </tr>
        <tr>
            <td width="22%" valign="top" class="vncellreq">下行带宽</td>
            <td width="78%" class="vtable">
                <input autocomplete='off' name="down" type="text" class="formfldalias" id="address" size="30" value="<?=htmlspecialchars($pconfig['down']); ?>">
                <select name="down_unit" class="formselect">
                   <option value="Kb" <?php if($pconfig['down_unit'] == 'Kb') echo 'selected'; ?>>Kbit/s</option>
                   <option value="Mb" <?php if($pconfig['down_unit'] == 'Mb') echo 'selected'; ?>>Mbit/s</option>
                   <option value="KB" <?php if($pconfig['down_unit'] == 'KB') echo 'selected'; ?>>KByte/s</option>
                   <option value="MB" <?php if($pconfig['down_unit'] == 'MB') echo 'selected'; ?>>MByte/s</option>
                </select>
            </td>
        </tr>
        <tr>
            <td width="22%" valign="top" class="vncellreq">类型</td>
            <td width="78%" class="vtable">
                <select name="method" class="formselect" onchange="method_change();">
                    <option value="limit" <?php if($pconfig['method'] == 'limit') echo 'selected'; ?>>独占</option>
                    <option value="share" <?php if($pconfig['method'] != 'limit') echo 'selected'; ?>>共享</option>
                </select>
                <span id="span_sharetype">
                <input type="radio"  name="sharetype" value="preemptive" <?php if($pconfig['method'] != 'average' && $pconfig['method'] != 'weight') echo "checked"; ?> onclick="method_change();">抢占式
                <input type="radio"  name="sharetype" value="average" <?php if($pconfig['method'] == 'average') echo "checked"; ?> onclick="method_change();">均分式
                <input type="radio"  name="sharetype" value="weight" <?php if($pconfig['method'] == 'weight') echo "checked"; ?> onclick="method_change();">自定义
                </span><br>
                <span class="vexpl">独占模式：定义限速范围内单台主机能获的最高带宽。<br>
                  共享模式：定义限速范围内所有主机能使用的最高带宽。
                </span>
            </td>
        </tr>
        <tr id="tr_adv_txt">
            <td width="22%" valign="top" class="vncellreq">自定义共享编辑</td>
            <td width="78%" class="vtable">
                <textarea id="adv_txt" name="adv_txt" cols=40 rows=15><?=htmlspecialchars($pconfig['adv_txt']); ?></textarea><br>
                <span class="vexpl">格式：地址,权值 例如：<br>172.16.8.0/30,50<br>172.16.8.100,50<br>
                1.每行输入一条规则。<br>
                2.地址可以是IP地址，别名，网段。<br>
                3.权值在1-100之间。带宽不足时不同规则分得的带宽为该规则权值占总权值的百分比。<br>
                </span>
            </td>            
        </tr>
        <tr id="tr_ip">
            <td width="22%" valign="top" class="vncellreq">局域网IP地址</td>
            <td width="78%" class="vtable">
                <input name="not" type="checkbox" id="not" value="yes" <?php if ($pconfig['not']) echo "checked"; ?>>
                <strong>取反</strong>
                <br />
                <table border="0" cellspacing="0" cellpadding="0">
                    <tr>
                        <td>类型：&nbsp;&nbsp;</td>
                        <td>
                            <select name="type" class="formselect" onChange="typesel_change()">
<?php
                                $sel = is_specialnet($pconfig['ip']); ?>
                                <option value="any"     <?php if ($pconfig['ip'] == "any") { echo "selected"; } ?>>全部</option>
                                <option value="single"  <?php if (($pconfig['mask'] == 32) && !$sel) { echo "selected"; $sel = 1; } ?>>单个IP地址或别名</option>
                                <option value="network" <?php if (!$sel) echo "selected"; ?>>网段</option>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td>地址：&nbsp;&nbsp;</td>
                        <td>
                            <input autocomplete='off' name="ip" type="text" class="formfldalias" id="ip" size="20" value="<?php if (!is_specialnet($pconfig['ip'])) echo htmlspecialchars($pconfig['ip']);?>"> /
                            <select name="mask" class="formselect" id="mask">
<?php                       for ($i = 31; $i > 0; $i--): ?>
                                <option value="<?=$i;?>" <?php if ($i == $pconfig['mask']) echo "selected"; ?>><?=$i;?></option>
<?php                       endfor; ?>
                            </select>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
        
        <tr id="tr_port">
            <td width="22%" valign="top" class="vncellreq">目的端口</td>
            <td width="78%" class="vtable">
                <table border="0" cellspacing="0" cellpadding="0">
                    <tr>
                        <td>from:&nbsp;&nbsp;</td>
                        <td>
                            <select name="beginport" class="formselect" onchange="rep_change();ext_change()">
                                <option value="">(other)</option>
                                <option value="any" <?php $bfound = 0; if ($pconfig['beginport'] == "any") { echo "selected"; $bfound = 1; } ?>>any</option>
<?php                           foreach ($wkports as $wkport => $wkportdesc): ?>
                                    <option value="<?=$wkport;?>" <?php if ($wkport == $pconfig['beginport']) { echo "selected"; $bfound = 1; }?>><?=htmlspecialchars($wkportdesc);?></option>
<?php                           endforeach; ?>
                            </select>
                            <input autocomplete='off' class="formfldalias" name="beginport_cust" id="beginport_cust" type="text" size="5" value="<?php if (!$bfound && $pconfig['beginport']) echo $pconfig['beginport']; ?>">
                        </td>
                    </tr>
                    <tr>
                        <td>to:</td>
                        <td>
                            <select name="endport" class="formselect" onchange="ext_change()">
                                <option value="">(other)</option>
                                <option value="any" <?php $bfound = 0; if ($pconfig['endport'] == "any") { echo "selected"; $bfound = 1; } ?>>any</option>
<?php                           foreach ($wkports as $wkport => $wkportdesc): ?>
                                    <option value="<?=$wkport;?>" <?php if ($wkport == $pconfig['endport']) { echo "selected"; $bfound = 1; } ?>><?=htmlspecialchars($wkportdesc);?></option>
<?php                           endforeach; ?>
                            </select>
                            <input autocomplete='off' class="formfldalias" name="endport_cust" id="endport_cust" type="text" size="5" value="<?php if (!$bfound && $pconfig['endport']) echo $pconfig['endport']; ?>">
                        </td>
                    </tr>
                </table>
                <br />
                <span class="vexpl">
                    填写目的地址的端口或端口范围。<br />
                    提示：在<em>'to'</em>字段留空如果你想指定单个端口。
                </span>
            </td>
        </tr>        
        
        
        <tr>
            <td width="22%" valign="top" class="vncell">描述</td>
            <td width="78%" class="vtable">
                <input name="descr" type="text" class="formfld unknown" id="descr" size="52" maxlength="52" value="<?=htmlspecialchars($pconfig['descr']);?>">
                <br />
                <span class="vexpl">您可以在这里输入一些描述作为参考。</span>
            </td>
        </tr>
        <tr>
            <td width="22%" valign="top">&nbsp;</td>
            <td width="78%">
                <input name="Submit" type="submit" class="formbtn" value="保存">  <input type="button" class="formbtn" value="取消" onclick="history.back()">
<?php           if (isset($id) && $a_pipe[$id]): ?>
                    <input name="id" type="hidden" value="<?=$id;?>">
<?php           endif; ?>
            </td>
        </tr>
    </table>
</form>
<script language="JavaScript">
<!--
    typesel_change();
    method_change();

<?php
    $isfirst = 0;
    $aliases = "";
    $addrisfirst = 0;
    $aliasesaddr = "";
    if($config['aliases']['alias'] <> "" and is_array($config['aliases']['alias']))
        foreach($config['aliases']['alias'] as $alias_name) {
            if(!stristr($alias_name['address'], ".")) {
                if($isfirst == 1) $aliases .= ",";
                $aliases .= "'" . $alias_name['name'] . "'";
                $isfirst = 1;
            } else {
                if($addrisfirst == 1) $aliasesaddr .= ",";
                $aliasesaddr .= "'" . $alias_name['name'] . "'";
                $addrisfirst = 1;
            }
        }
?>

    var addressarray=new Array(<?php echo $aliasesaddr; ?>);
    var customarray=new Array(<?php echo $aliases; ?>);

//-->
</script>
<?php include("fend.inc"); ?>
</body>
</html>

